package demo.vo;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import demo.java.net.HttpDemo;
import demo.vo.http.ResponseVo;
import org.apache.commons.lang3.StringUtils;

import java.util.HashSet;
import java.util.Set;

public class DnsVo {
    static final Set<String> monitorDomain = new HashSet<>();
    String domain;
    String ips;

    public String getDomain() {
        return domain;
    }

    public void setDomain(String domain) {
        this.domain = domain;
    }

    public String getIps() {
        return ips;
    }

    public void setIps(String ips) {
        this.ips = ips;
    }

    public int getIpCnt() {
        if (StringUtils.isBlank(ips)) {
            return 0;
        }
        return ips.split(";").length;
    }

    public int getDomainResponseCode() {
        String url = "http://" + domain;
        try {
            return HttpDemo.get(url, 1000, 3000).getResponseCode();
        } catch (Exception e) {
            return -1;
        }
    }

    public int getDomainHealthCheckCode() {
        String url = "http://" + domain + "/healthcheck";
        try {
            return HttpDemo.get(url, 1000, 3000).getResponseCode();
        } catch (Exception e) {
            return -1;
        }
    }

    public boolean isMonitor() {
        synchronized (monitorDomain) {
            if (monitorDomain.isEmpty()) {
                try {
                    String url = "https://op3.ximalaya.com/thanos/api/v1/query?query=nginx_http_request_duration_seconds_count";
                    ResponseVo responseVo = HttpDemo.get(url, 1000, 9000);
                    String content = responseVo.getContent();
                    JSONObject json = JSON.parseObject(content);
                    JSONObject data = json.getJSONObject("data");
                    JSONArray jsonArray = data.getJSONArray("result");
                    for (int i = 0; i < jsonArray.size(); i++) {
                        JSONObject item = jsonArray.getJSONObject(i);
                        String domain = item.getJSONObject("metric").getString("host");
                        monitorDomain.add(domain);
                    }
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        }

        return monitorDomain.contains(domain);
    }
}
